package com.example.demo.controller;


import com.alibaba.fastjson.JSONObject;
import com.diboot.core.util.JSON;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Status;
import com.example.demo.entity.AttributeEntity;
import com.example.demo.entity.BusinessEntity;
import com.example.demo.service.IDsBusinessService;
import com.example.demo.service.IDsEntityService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 实体属性定义扩展 前端控制器
 * </p>
 *
 * @author dxd
 * @since 2020-09-03
 */
@RestController
@RequestMapping("/manage/entity")
public class DsEntityController {

    private static final Log logger = LogFactory.getLog(DsEntityController.class);


    @Autowired
    IDsEntityService service;
    @Autowired
    IDsBusinessService businessService;

    @PostMapping("create")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult object(@RequestBody BusinessEntity entity) {
        businessService.removeByBusi(entity.getBusinessType());
        service.removeByBusi(entity.getBusinessType());

        businessService.save(entity);
        entity.getAttributeList().forEach(
                m -> {
                    m.setBusinessName(entity.getBusinessName());
                    m.setBusinessType(entity.getBusinessType());
                    service.save(m);
                });

        return JsonResult.OK(Status.OK);
    }

    @PostMapping("list")
    public JsonResult list(@RequestBody(required = false) BusinessEntity entity) {
        return JsonResult.OK(service.list());
    }

    @PostMapping("list1")
    public JsonResult list1(@RequestBody(required = false) BusinessEntity entity) {
        List<AttributeEntity> list2 = service.list();
        List<Map> lmaps = new ArrayList<>(20);
        list2.forEach(entity1 -> {
            logger.info("===========================");
            logger.info(entity1.getExtensions());
            String t1 = JSON.parseObject(entity1.getExtensions(),String.class);
            JSONObject t = JSON.parseObject(t1);
            t.putAll(BeanMap.create(entity1));
            lmaps.add(t);
        });
        return JsonResult.OK(lmaps);
    }


    @PostMapping("tables")
    public JsonResult list() {
        return JsonResult.OK(businessService.listTables());
    }

    @PostMapping("columns")
    public JsonResult columns(@RequestParam("businessType") String businessType) {
        return JsonResult.OK(service.listcolumns(businessType));
    }
}
